package com.example.auth.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.auth.consts.IndexConst;
import com.example.auth.entity.SysUser;
import com.example.auth.excel.SysUserImportExcel;
import com.example.auth.exception.LyException;
import com.example.auth.mapper.SysUserMapper;
import com.example.auth.service.SysUserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @author: LiYang
 * @create: 2023-07-14 09:05
 * @Description:
 * @Version 1.0
 **/
@Slf4j
@Component
public class SysUserListener implements ReadListener<SysUserImportExcel> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 10;
    /**
     * 缓存的数据
     */
    private List<SysUser> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    @Transactional(rollbackFor = {Throwable.class})
    public void invoke(@Valid SysUserImportExcel sysUserImportExcel, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(sysUserImportExcel));
        sysUserImportExcel.setPassword(passwordEncoder.encode(sysUserImportExcel.getPassword()));
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserImportExcel,sysUser);
        if("有效".equals(sysUserImportExcel.getStatusValue())){
            sysUser.setStatus(IndexConst.EFFECTIVE_VALUE);
        }else if ("无效".equals(sysUserImportExcel.getStatusValue())){
            sysUser.setStatus(IndexConst.INVALID_VALUE);
        }else {
            throw new LyException("导入的数据出错");
        }
        if("男".equals(sysUserImportExcel.getGenderValue())){
            sysUser.setGender(IndexConst.MAN_VALUE);
        }else if ("女".equals(sysUserImportExcel.getGenderValue())){
            sysUser.setGender(IndexConst.WOMAN_VALUE);
        }else {
            throw new LyException("导入的数据出错");
        }
        //已经有的用户不进行导入
        String username = sysUser.getUsername();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username);
        if(!ObjectUtils.isEmpty(sysUserMapper.selectOne(wrapper))){
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            throw new LyException("数据相同，请检查数据");
        }
        cachedDataList.add(sysUser);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }



    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        sysUserMapper.batchInsert(cachedDataList);
        log.info("存储数据库成功！");
        cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    }

}
